package org.f0rb.demo.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;


/**
 * Created by IntelliJ IDEA.
 * Date: 2010-2-25
 * Time: 21:48:34
 *
 * @author f0rb
 */
@SuppressWarnings("unused")
public class RequestUtils {
    private RequestUtils() {
    }

    public static Cookie createCookie(HttpServletRequest request, String name, String value) {
        return createCookie(request, name, value, 0);
    }

    public static Cookie createCookie(HttpServletRequest request, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);
        String domain = request.getServerName();
        if (domain != null && domain.indexOf('.') != -1) {
            cookie.setDomain('.' + domain);
        }
        cookie.setPath("/");
        return cookie;
    }

    /**
     * 获取COOKIE.
     *
     * @param request HttpServletRequest Object
     * @param name    the name of the cookie
     * @return The cookie named $name if exists, otherwise null.
     */
    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) return null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equalsIgnoreCase(name)) return cookie;
        }
        return null;
    }

    /**
     * 获取COOKIE的值.
     *
     * @param request HttpServletRequest Object
     * @param name    the name of the cookie
     * @return The cookie's value named $name if exists, otherwise null.
     */
    public static String getCookieValue(HttpServletRequest request, String name) {
        Cookie cookie = getCookie(request, name);
        return cookie == null ? null : cookie.getValue();
    }

    /**
     * 获取header信息，名字大小写无关.
     *
     * @param request HttpServletRequest Object
     * @param name    the name of the header
     * @return the header's value correspond to the name
     */
    public static String getHeader(HttpServletRequest request, String name) {
        String value = request.getHeader(name);
        if (value != null) return value;
        Enumeration<?> names = request.getHeaderNames();
        while (names.hasMoreElements()) {
            String n = (String) names.nextElement();
            if (n.equalsIgnoreCase(name)) {
                return request.getHeader(n);
            }
        }
        return null;
    }

    /**
     * 获取客户端IP地址，此方法用在proxy环境中.
     *
     * @param request HttpServletRequest Object
     * @return Remote Address
     */
    public static String getRemoteAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotBlank(ip)) {
            String[] ips = StringUtils.split(ip, ',');
            if (ips != null) {
                for (String tmpip : ips) {
                    if (StringUtils.isBlank(tmpip))
                        continue;
                    tmpip = tmpip.trim();
                    if (StringUtils.isIPAddr(tmpip) && !tmpip.startsWith("10.")
                            && !tmpip.startsWith("192.168.") && !"127.0.0.1".equals(tmpip)) {
                        return tmpip.trim();
                    }
                }
            }
        }
        ip = request.getHeader("x-real-ip");
        if (StringUtils.isIPAddr(ip))
            return ip;
        ip = request.getRemoteAddr();
        if (ip.indexOf('.') == -1)
            ip = "127.0.0.1";
        return ip;
    }

    /**
     * 判断是否为搜索引擎.
     *
     * @param request HttpServletRequest Object
     * @return true if the "user-agent" contains certain string below, otherwise false
     */
    public static boolean isRobot(HttpServletRequest request) {
        String ua = request.getHeader("user-agent");
        return StringUtils.isNotBlank(ua)
                && (ua.contains("Baiduspider")
                || ua.contains("Googlebot")
                || ua.contains("sogou")
                || ua.contains("sina")
                || ua.contains("iaskspider")
                || ua.contains("ia_archiver")
                || ua.contains("Sosospider")
                || ua.contains("YoudaoBot")
                || ua.contains("yahoo")
                || ua.contains("yodao")
                || ua.contains("MSNBot")
                || ua.contains("spider")
                || ua.contains("Twiceler")
                || ua.contains("Sosoimagespider")
                || ua.contains("naver.com/robots")
                || ua.contains("Nutch")
                || ua.contains("spider"));
    }

    /**
     * 获取HTTP端口.
     *
     * @param request HttpServletRequest Object
     * @return Http Port
     */
    public static int getHttpPort(HttpServletRequest request) {
        try {
            return new URL(request.getRequestURL().toString()).getPort();
        } catch (MalformedURLException e) {
            return 80;
        }
    }

    public static String getWebUrl(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
    }
}
